﻿using System;
using System.Xml.Linq;

namespace SharePoint.Orm.Caml {
	public class CamlFieldRef {
		public string FieldName { get; set; }
		public bool? Ascending { get; set; }

		public CamlFieldRef(string fieldName) {
			FieldName = fieldName;
		}

		public bool IsAscending {
			get { return Ascending == null || Ascending.Value; }
		}

		public XElement ToXml() {
			XElement fieldRefElement = new XElement("FieldRef", new XAttribute("Name", FieldName));
			if (Ascending != null) {
				fieldRefElement.Add(new XAttribute("Ascending", Ascending.Value ? "TRUE" : "FALSE"));
			}
			return fieldRefElement;
		}

		public static CamlFieldRef Parse(XElement element) {
			XAttribute nameAttr = element.Attribute("Name");
			if (nameAttr == null) {
				throw new Exception("Expected name attribute on FieldRef element");
			}
			string fieldName = nameAttr.Value;
			CamlFieldRef result = new CamlFieldRef(fieldName);

			XAttribute ascendingAttr = element.Attribute("Ascending");
			if (ascendingAttr != null) {
				result.Ascending = bool.Parse(ascendingAttr.Value);
			}

			return result;
		}
	}
}
